import { routes } from '@/router'
import { userInfo, logout } from '@/api/login'
import { handleRouter } from '@/utils'
import { resetRouter } from '@/router'
export default {
  // namespaced: true,
  state: {
    routes: [],
    resourceSet: [],
    userName: '',
    roleType: '',
    userId: '',
    mobile: '',
    userData: {},
  },
  mutations: {
    RESOURCE_SET: (state, value) => {
      state.resourceSet = value
    },
    FILTER_ROUTES: (state, value) => {
      state.routes = value
    },
    USER_NAME: (state, value) => {
      state.userName = value
    },
    ROLE_TYPE: (state, value) => {
      state.roleType = value
    },
    USER_ID: (state, value) => {
      state.userId = value
    },
    MOBILE: (state, value) => {
      state.mobile = value
    },
    USER_DATA: (state, value) => {
      state.userData = value
    },
  },
  actions: {
    // 存储全局权限集
    getGlobalResourceSet({ commit }) {
      return new Promise((resolve, reject) => {
        userInfo()
          .then((res) => {
            let permissionList = res.systemUserRole.resources
            const filterRouters = handleRouter(permissionList, routes)
            commit('FILTER_ROUTES', filterRouters)
            commit('RESOURCE_SET', permissionList)
            commit('USER_NAME', res.userName)
            commit('ROLE_TYPE', res.type)
            commit('USER_ID', res.id)
            commit('MOBILE', res.mobile)
            commit('USER_DATA', res)
            resolve(Array.from(new Set(permissionList)))
          })
          .catch(() => {
            reject()
          })
      })
    },
    handleLogOut({ commit }) {
      return new Promise((resolve, reject) => {
        logout()
          .then(() => {
            localStorage.clear()
            commit('RESET_ALL_STATE', null, { root: true })
            resetRouter()
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // token 过期
    fedLogOut({ commit }) {
      return new Promise((resolve) => {
        localStorage.clear()
        commit('RESET_ALL_STATE', null, { root: true })
        resetRouter()
        resolve()
      })
    },
  },
}
